package com.bit.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.bit.common.security.aspect.NotRequireLogin;
import com.bit.common.security.service.TokenService;
import com.bite.common.core.contants.Constants;
import com.bite.common.core.contants.HttpConstants;
import com.bite.common.core.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


//拦截器是绑定在具体的服务上
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;


    //从system中拿,从哪个配置文件读取,取决于当前bean在哪个容器下面被管理
    @Value("${jwt.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.getMethod().isAnnotationPresent(NotRequireLogin.class)) {
            return true; // 如果没有标记 @RequireLogin，直接放行
        }

        String token = getToken(request);

        Claims claims = tokenService.getClaims(token, secret);
        Long userId = tokenService.getUserId(token, secret);
        String userKey = tokenService.getUserKey(claims);
        ThreadLocalUtil.set(Constants.USER_ID,userId);
        ThreadLocalUtil.set(Constants.USER_KEY,userKey);
        tokenService.extendToken(claims);
        return true;
    }

    private String getToken(HttpServletRequest request){
        //token携带在请求头当中
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if (StrUtil.isNotEmpty(token)  && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理
        ThreadLocalUtil.remove();
    }
}
